package com.shenda.log;

import java.util.concurrent.atomic.AtomicLong;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.shenda.device.Options;
import com.swak.utils.StringUtils;
import com.swak.utils.time.DateTimes;

import io.vertx.core.Handler;
import io.vertx.core.http.HttpServerRequest;
import io.vertx.ext.web.RoutingContext;

/**
 * 系统请求的日志记录
 * 
 * @author lifeng
 * @date 2020年5月24日 下午3:52:20
 */
public class LogHandler implements Handler<RoutingContext> {

	/**
	 * 设备日志
	 */
	Logger logger = LoggerFactory.getLogger(Options.class);

	/**
	 * 访问计数
	 */
	AtomicLong count = new AtomicLong(0);

	@Override
	public void handle(RoutingContext context) {
		context.response().endHandler((v) -> {
			String log = StringUtils.format("%s\t%s\t%s\t%s", count.incrementAndGet(), getRemoteAddr(context.request()),
					DateTimes.getFormatNow("yyyy-MM-dd HH:mm:ss"), context.request().uri());
			logger.info(log);
		});
		context.next();
	}

	/**
	 * 获得用户远程地址
	 */
	public String getRemoteAddr(HttpServerRequest request) {
		String remoteAddr = request.getHeader("X-Real-IP");
		if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("X-Forwarded-For");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("Proxy-Client-IP");
		} else if (StringUtils.isBlank(remoteAddr)) {
			remoteAddr = request.getHeader("WL-Proxy-Client-IP");
		}
		return remoteAddr != null ? remoteAddr
				: (request.remoteAddress() != null ? request.remoteAddress().host() : null);
	}
}
